package com.hb.trade.server.project.evaluation.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.enums.MemberTypeEnum;
import com.hb.core.pojo.project.evaluation.dto.EvaluationCommitteeDTO;
import com.hb.core.pojo.project.evaluation.dto.EvaluationCommitteeMembersDTO;
import com.hb.core.pojo.project.evaluation.entity.EvaluationCommittee;
import com.hb.core.pojo.project.evaluation.entity.EvaluationCommitteeAvoidOrg;
import com.hb.core.pojo.project.evaluation.entity.EvaluationCommitteeBid;
import com.hb.core.pojo.project.evaluation.entity.EvaluationCommitteeMembers;
import com.hb.core.pojo.project.evaluation.mapper.EvaluationMapper;
import com.hb.core.pojo.project.proj.entity.BidInviterVO;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.trade.server.project.evaluation.service.EvaluationCommitteeAvoidOrgService;
import com.hb.trade.server.project.evaluation.service.EvaluationCommitteeBidService;
import com.hb.trade.server.project.evaluation.service.EvaluationCommitteeMembersService;
import com.hb.trade.server.project.evaluation.service.EvaluationCommitteeService;
import org.fzzn.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 评标委员会信息 服务实现类
 * </p>
 *
 * @author zhaojk
 * @since 2021-08-30
 * @updater ljs
 */
@Service
public class EvaluationCommitteeServiceImpl extends ServiceImpl<EvaluationMapper, EvaluationCommittee> implements EvaluationCommitteeService {

    @Autowired
    private EvaluationCommitteeBidService evaluationCommitteeBidService;

    @Autowired
    private EvaluationCommitteeMembersService evaluationCommitteeMembersService;

    @Autowired
    private EvaluationCommitteeAvoidOrgService evaluationCommitteeAvoidOrgService;

    @Override
    public Page<BidSection> listNotSelectSection(EvaluationCommitteeDTO evaluationCommitteeDTO) {
        return baseMapper.listNotSelectSectionByProjectId(evaluationCommitteeDTO.pages(), evaluationCommitteeDTO);
    }

    @Override
    public Page<EvaluationCommittee> pageEvaluationCommittee(EvaluationCommitteeDTO evaluationCommitteeDTO) {
        return baseMapper.pageEvaluationCommittee(evaluationCommitteeDTO.pages(), evaluationCommitteeDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveEvaluationCommittee(EvaluationCommitteeDTO evaluationCommitteeDTO) {
        //处理主表信息
        // 专家数量
        Integer expertNum = 0;
        // 招标人代表数量
        Integer bidInviterNum = 0;
        // 评委会成员总数量（专家+招标人代表）
        Integer evaluationCommitteeNum = 0;
        expertNum = evaluationCommitteeDTO.getExpertList().size() + evaluationCommitteeDTO.getRandomExpertList().size();
        bidInviterNum = evaluationCommitteeDTO.getBidInviterList().size();
        evaluationCommitteeNum = expertNum + bidInviterNum;
        evaluationCommitteeDTO.setId(IdUtil.getId());
        evaluationCommitteeDTO.setEvaluationCommitteeNum(evaluationCommitteeNum);
        evaluationCommitteeDTO.setEvaluationExpertNum(expertNum);
        evaluationCommitteeDTO.setTenderNum(bidInviterNum);
        save(evaluationCommitteeDTO);

        // 处理标段ID
        List<BidSection> sectionList = evaluationCommitteeDTO.getSectionList();
        if (CollUtil.isNotEmpty(sectionList)) {
            List<EvaluationCommitteeBid> evaluationCommitteeBids = new ArrayList<>();
            for (BidSection bidSection : sectionList) {
                evaluationCommitteeBids.add(new EvaluationCommitteeBid(bidSection.getId(), evaluationCommitteeDTO.getId()));
            }
            evaluationCommitteeBidService.saveBatch(evaluationCommitteeBids);
        }

        // 处理专家ID
        List<EvaluationCommitteeMembersDTO> expertList = evaluationCommitteeDTO.getExpertList();
        List<EvaluationCommitteeMembers> evaluationCommitteeMembers = new ArrayList<>();
        if (CollUtil.isNotEmpty(expertList)) {
            for (EvaluationCommitteeMembersDTO expertInfo : expertList) {
                // 随机生成的六位数密码
                EvaluationCommitteeMembers member = expertInfo.to(EvaluationCommitteeMembers.class);
                member.setMemberType(MemberTypeEnum.EXPERT.getCode());
                member.setEvaluationCommitteeId(evaluationCommitteeDTO.getId());
                member.setPassword(randomPassword());
                member.setId(null);
                member.setMemberId(expertInfo.getId());
                member.buildBaseData(1);
                evaluationCommitteeMembers.add(member);
            }
        }
        //处理随机抽取专家
        List<EvaluationCommitteeMembersDTO> randomExpertList = evaluationCommitteeDTO.getRandomExpertList();
        if (CollUtil.isNotEmpty(randomExpertList)) {
            for (EvaluationCommitteeMembersDTO randomExpertInfo : randomExpertList) {
                EvaluationCommitteeMembers randomMember = randomExpertInfo.to(EvaluationCommitteeMembers.class);
                randomMember.setMemberType(MemberTypeEnum.RANDOM_EXPERT.getCode());
                randomMember.setEvaluationCommitteeId(evaluationCommitteeDTO.getId());
                randomMember.setPassword(randomPassword());
                randomMember.setId(null);
                randomMember.setMemberId(randomExpertInfo.getId());
                randomMember.buildBaseData(1);
                evaluationCommitteeMembers.add(randomMember);

            }
        }
        //处理招标人代理
        List<EvaluationCommitteeMembers> userListVOList = evaluationCommitteeDTO.getBidInviterList();
        if (CollUtil.isNotEmpty(userListVOList)) {
            for (EvaluationCommitteeMembers bidInviterVO : userListVOList) {
                EvaluationCommitteeMembers bidInviterMember = bidInviterVO.to(EvaluationCommitteeMembers.class);
                bidInviterMember.setMemberType(MemberTypeEnum.BID_INVITER.getCode());
                bidInviterMember.setEvaluationCommitteeId(evaluationCommitteeDTO.getId());
                bidInviterMember.setPassword(randomPassword());
                bidInviterMember.setMemberId(bidInviterVO.getId());
                bidInviterMember.setId(null);
                bidInviterMember.buildBaseData(1);
                evaluationCommitteeMembers.add(bidInviterMember);
            }
        }
        evaluationCommitteeMembersService.saveBatch(evaluationCommitteeMembers);

        // 查询是否已经指派了组长  如果指派了组长需要修改投票人的id
        List<EvaluationCommitteeMembers> bidCandidateSectionList = evaluationCommitteeMembersService.list(
                new LambdaQueryWrapper<EvaluationCommitteeMembers>()
                        .eq(EvaluationCommitteeMembers::getEvaluationCommitteeId, evaluationCommitteeDTO.getId())
                        .eq(EvaluationCommitteeMembers::getChairmanFlag, "1"));
        if (CollUtil.isNotEmpty(bidCandidateSectionList)) {
            // 说明设置了组长 将所有的组员投票设置为组长id
            Long leaderId = bidCandidateSectionList.get(0).getId();

            EvaluationCommitteeMembers updateInfo = new EvaluationCommitteeMembers();
            updateInfo.setLeaderId(leaderId);
            QueryWrapper updateWrapper = new QueryWrapper();
            updateWrapper.eq("evaluation_committee_id", evaluationCommitteeDTO.getId());
            evaluationCommitteeMembersService.update(updateInfo, updateWrapper);
        }

        //处理回避单位
        List<EvaluationCommitteeAvoidOrg> evaluationCommitteeAvoidOrgList = evaluationCommitteeDTO.getAvoidOrgList();
        if (CollUtil.isNotEmpty(evaluationCommitteeAvoidOrgList)) {
            List<EvaluationCommitteeAvoidOrg> evaluationCommitteeAvoidOrgs = new ArrayList<>();
            for (EvaluationCommitteeAvoidOrg evaluationCommitteeAvoidOrg : evaluationCommitteeAvoidOrgList) {
                evaluationCommitteeAvoidOrg.setId(null);
                evaluationCommitteeAvoidOrg.buildBaseData(1);
                evaluationCommitteeAvoidOrg.setEvaluationCommitteeId(evaluationCommitteeDTO.getId());
                evaluationCommitteeAvoidOrgs.add(evaluationCommitteeAvoidOrg);
            }
            evaluationCommitteeAvoidOrgService.saveBatch(evaluationCommitteeAvoidOrgs);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateEvaluationCommittee(EvaluationCommitteeDTO evaluationCommitteeDTO) {
        //处理主表信息
        // 专家数量
        Integer expertNum = 0;
        // 招标人代表数量
        Integer bidInviterNum = 0;
        // 评委会成员总数量（专家+招标人代表）
        Integer evaluationCommitteeNum = 0;
        expertNum = evaluationCommitteeDTO.getExpertList().size() + evaluationCommitteeDTO.getRandomExpertList().size();
        bidInviterNum = evaluationCommitteeDTO.getBidInviterList().size();
        evaluationCommitteeNum = expertNum + bidInviterNum;
        evaluationCommitteeDTO.setEvaluationCommitteeNum(evaluationCommitteeNum);
        evaluationCommitteeDTO.setEvaluationExpertNum(expertNum);
        evaluationCommitteeDTO.setTenderNum(bidInviterNum);
        evaluationCommitteeDTO.buildBaseData(2);
        updateById(evaluationCommitteeDTO);

        Long evaluationCommitteeId = evaluationCommitteeDTO.getId();
        // 处理标段ID  先删后插
        evaluationCommitteeBidService.remove(new LambdaQueryWrapper<EvaluationCommitteeBid>().eq(EvaluationCommitteeBid::getEvaluationCommitteeId, evaluationCommitteeId));
        List<BidSection> sectionList = evaluationCommitteeDTO.getSectionList();
        if (CollUtil.isNotEmpty(sectionList)) {
            List<EvaluationCommitteeBid> evaluationCommitteeBids = new ArrayList<>();
            for (BidSection bidSection : sectionList) {
                evaluationCommitteeBids.add(new EvaluationCommitteeBid(bidSection.getId(), evaluationCommitteeDTO.getId()));
            }
            evaluationCommitteeBidService.saveBatch(evaluationCommitteeBids);
        }

        // 处理专家ID  先删后插
        evaluationCommitteeMembersService.remove(new LambdaQueryWrapper<EvaluationCommitteeMembers>().eq(EvaluationCommitteeMembers::getEvaluationCommitteeId, evaluationCommitteeId));
        List<EvaluationCommitteeMembers> evaluationCommitteeMembers = new ArrayList<>();
        List<EvaluationCommitteeMembersDTO> expertList = evaluationCommitteeDTO.getExpertList();
        if (CollUtil.isNotEmpty(expertList)) {
            for (EvaluationCommitteeMembersDTO expertInfo : expertList) {
                EvaluationCommitteeMembers member = expertInfo.to(EvaluationCommitteeMembers.class);
                member.setMemberType(MemberTypeEnum.EXPERT.getCode());
                member.setEvaluationCommitteeId(evaluationCommitteeDTO.getId());
                member.setPassword(randomPassword());
                member.setId(null);
                member.setMemberId(expertInfo.getId());
                member.buildBaseData(1);
                evaluationCommitteeMembers.add(member);
            }
        }

        //处理随机抽取专家
        List<EvaluationCommitteeMembersDTO> randomExpertList = evaluationCommitteeDTO.getRandomExpertList();
        if (CollUtil.isNotEmpty(randomExpertList)) {
            for (EvaluationCommitteeMembersDTO randomExpertInfo : randomExpertList) {
                EvaluationCommitteeMembers randomMember = randomExpertInfo.to(EvaluationCommitteeMembers.class);
                randomMember.setMemberType(MemberTypeEnum.RANDOM_EXPERT.getCode());
                randomMember.setEvaluationCommitteeId(evaluationCommitteeDTO.getId());
                randomMember.setPassword(randomPassword());
                randomMember.setId(null);
                randomMember.setMemberId(randomExpertInfo.getId());
                randomMember.buildBaseData(1);
                evaluationCommitteeMembers.add(randomMember);

            }
        }

        //处理招标人代理  先删后插
        List<EvaluationCommitteeMembers> userListVOList = evaluationCommitteeDTO.getBidInviterList();
        if (CollUtil.isNotEmpty(userListVOList)) {
            for (EvaluationCommitteeMembers bidInviterVO : userListVOList) {
                EvaluationCommitteeMembers bidInviterMember = bidInviterVO.to(EvaluationCommitteeMembers.class);
                bidInviterMember.setMemberType(MemberTypeEnum.BID_INVITER.getCode());
                bidInviterMember.setEvaluationCommitteeId(evaluationCommitteeDTO.getId());
                bidInviterMember.setPassword(randomPassword());
                bidInviterMember.setMemberId(bidInviterVO.getId());
                bidInviterMember.setId(null);
                bidInviterMember.buildBaseData(1);
                evaluationCommitteeMembers.add(bidInviterMember);
            }
        }
        evaluationCommitteeMembersService.saveBatch(evaluationCommitteeMembers);

        // 查询是否已经指派了组长  如果指派了组长需要修改投票人的id
        List<EvaluationCommitteeMembers> bidCandidateSectionList = evaluationCommitteeMembersService.list(
                new LambdaQueryWrapper<EvaluationCommitteeMembers>()
                        .eq(EvaluationCommitteeMembers::getEvaluationCommitteeId, evaluationCommitteeDTO.getId())
                        .eq(EvaluationCommitteeMembers::getChairmanFlag, "1"));
        if (CollUtil.isNotEmpty(bidCandidateSectionList)) {
            // 说明设置了组长 将所有的组员投票设置为组长id
            Long leaderId = bidCandidateSectionList.get(0).getId();

            EvaluationCommitteeMembers updateInfo = new EvaluationCommitteeMembers();
            updateInfo.setLeaderId(leaderId);
            QueryWrapper updateWrapper = new QueryWrapper();
            updateWrapper.eq("evaluation_committee_id", evaluationCommitteeDTO.getId());
            evaluationCommitteeMembersService.update(updateInfo, updateWrapper);
        }
        //处理回避单位  先删后插
        evaluationCommitteeAvoidOrgService.remove(new LambdaQueryWrapper<EvaluationCommitteeAvoidOrg>().eq(EvaluationCommitteeAvoidOrg::getEvaluationCommitteeId, evaluationCommitteeId));
        List<EvaluationCommitteeAvoidOrg> evaluationCommitteeAvoidOrgList = evaluationCommitteeDTO.getAvoidOrgList();
        if (null != evaluationCommitteeAvoidOrgList) {
            List<EvaluationCommitteeAvoidOrg> evaluationCommitteeAvoidOrgs = new ArrayList<>();
            for (EvaluationCommitteeAvoidOrg evaluationCommitteeAvoidOrg : evaluationCommitteeAvoidOrgList) {
                evaluationCommitteeAvoidOrg.setId(null);
                evaluationCommitteeAvoidOrg.buildBaseData(1);
                evaluationCommitteeAvoidOrg.setEvaluationCommitteeId(evaluationCommitteeDTO.getId());
                evaluationCommitteeAvoidOrgs.add(evaluationCommitteeAvoidOrg);
            }
            evaluationCommitteeAvoidOrgService.saveBatch(evaluationCommitteeAvoidOrgs);
        }
        return true;
    }

    @Override
    public EvaluationCommittee findBySectionIdsAndEvaluationType(Long sectionId, Integer evaluationType) {
        return baseMapper.findBySectionIdsAndEvaluationType(sectionId, evaluationType);
    }

    @Override
    public Page<BidInviterVO> pageBidInviter(BidInviterVO bidInviterVO) {
        return baseMapper.pageBidInviter(bidInviterVO.pages(), bidInviterVO);
    }


    @Override
    public List<BidInviterVO> listBidInviterInfo(List<Long> bidInviterIds) {
        if (CollUtil.isEmpty(bidInviterIds)) {
            return null;
        }
        return baseMapper.listBidInviterInfo(bidInviterIds);
    }

    /**
     * 生成随机的六位数密码（整形）
     *
     * @return
     */
    public String randomPassword() {
        String randomNum = "";
        for (int i = 0; i < 6; i++){
            String num = RandomUtil.randomInt(10) + "";
            randomNum += num;
        }
        return randomNum;
    }

}
